const express = require('express');
const router = express.Router();
const writeData = require('../../db/module/writeData');
const readData = require('../../db/module/readData');
const delData = require('../../db/module/delData');
const { sysc_hottery_result, timing_Lottery_history } = require('../../utils/sysc_lottery_result');

// 常量定义
const INITIAL_DRAWS = 10;
const MAX_DRAW_NUMBER = 1000000;

// 获取历史数据（带分页）
router.post('/getLotteryHistory', async (req, res) => {
    try {
        const { type, page, size } = req.body;
        // 先验证彩种是否存在
        const lotteryType = await readData({ code: type }, 'lotteryTypes');
        if (lotteryType.data.length === 0) {
            return res.send({ code: 400, msg: '无效的彩票类型' });
        }

        const params = { type, page, size, sort: { drawNumber: -1 } };
        let result = await readData(params, 'lotteryHistory');

        // 按期号倒序排序（最新在前）
        result.data.sort((a, b) => b.drawNumber - a.drawNumber);

        res.send(result);
    } catch (error) {
        res.send({ code: 50000, msg: error.message });
    }
});

// 保存记录到历史
router.post('/saveToHistory', async (req, res) => {
    try {
        const { type, record } = req.body;
        // 验证彩种
        const lotteryType = await readData({ code: type }, 'lotteryTypes');
        if (lotteryType.data.length === 0) {
            return res.send({ code: 400, msg: '无效的彩票类型' });
        }

        const result = await saveToHistory(type, record);
        res.send({ code: 200, data: result });
    } catch (error) {
        res.send({ code: 50000, msg: error.message });
    }
});

// 增加记录接口
router.post('/addRecord', async (req, res) => {
    try {
        const {
            type,
            front,
            back,
            firstPrizeCount = 0,
            secondPrizeCount = 0,
            drawNumber
        } = req.body;

        // 验证彩种
        const lotteryTypeResult = await readData({ code: type }, 'lotteryTypes');
        if (lotteryTypeResult.data.length === 0) {
            return res.send({ code: 400, msg: '无效的彩票类型' });
        }
        const config = lotteryTypeResult.data[0];

        // 验证前后区号码
        if (!front || !Array.isArray(front) || front.length !== config.front.count) {
            return res.send({ code: 400, msg: `前区号码不合法，需${config.front.count}个号码` });
        }
        if (config.hasBack && (!back || !Array.isArray(back) || back.length !== config.back.count)) {
            return res.send({ code: 400, msg: `后区号码不合法，需${config.back.count}个号码` });
        }
        if (!config.hasBack && back && back.length > 0) {
            return res.send({ code: 400, msg: '当前彩种不支持后区号码' });
        }

        // 验证号码范围
        const isValidFront = front.every(num =>
            Number.isInteger(num) && num >= config.front.min && num <= config.front.max
        );
        let isValidBack = true;
        if (config.hasBack) {
            isValidBack = back.every(num =>
                Number.isInteger(num) && num >= config.back.min && num <= config.back.max
            );
        }

        if (!isValidFront) {
            return res.send({ code: 400, msg: `前区号码必须在${config.front.min}-${config.front.max}之间` });
        }
        if (config.hasBack && !isValidBack) {
            return res.send({ code: 400, msg: `后区号码必须在${config.back.min}-${config.back.max}之间` });
        }

        // 验证奖项数据
        if (!Number.isInteger(firstPrizeCount) || firstPrizeCount < 0) {
            return res.send({ code: 400, msg: '一等奖注数必须为非负整数' });
        }
        if (!Number.isInteger(secondPrizeCount) || secondPrizeCount < 0) {
            return res.send({ code: 400, msg: '二等奖注数必须为非负整数' });
        }

        // 验证期号
        if (!drawNumber || !Number.isInteger(drawNumber) || drawNumber <= 0) {
            return res.send({ code: 400, msg: '期号必须为正整数' });
        }

        // 检查期号是否已存在
        const history = await getHistory(type);
        const existingNumbers = new Set(history.map(item => item.drawNumber));
        if (existingNumbers.has(drawNumber)) {
            return res.send({ code: 400, msg: '期号已存在，请使用其他期号' });
        }

        // 准备记录
        const record = {
            front: [...front].sort((a, b) => a - b),
            back: config.hasBack ? [...back].sort((a, b) => a - b) : [],
            drawNumber,
            firstPrizeCount,
            secondPrizeCount,
            type,
            createTime: new Date().toISOString() // 添加创建时间
        };

        // 保存记录
        const result = await saveToHistory(type, record);

        res.send({
            code: 20000,
            msg: '记录添加成功',
            data: {
                drawNumber,
                ...result
            }
        });
    } catch (error) {
        res.send({ code: 50000, msg: error.message });
    }
});

// 同步开奖结果
router.post('/syncLotteryResult', async (req, res) => {
    // 获取所有彩票种类
    const lotteryTypes = await readData({}, 'lotteryTypes');
    let successCount = 0
    let errorCount = 0
    let skipCount = 0
    for (let i = 0; i < lotteryTypes.data.length; i++) {
        let item = lotteryTypes.data[i]
        let result = await sysc_hottery_result(item.code)
        let lottery_result = result.data.data

        // 查询是否存在这一期数据
        let lookIsHistory = await readData({
            type: item.code,
            drawNumber: Number(lottery_result.issueno)
        }, 'lotteryHistory');
        if (lookIsHistory.total == 0) {
            // 转化请求数据
            let params = {
                "type": item.code,
                "typeName": item.name,
                "front": lottery_result.number.split(' '),
                "drawNumber": Number(lottery_result.issueno),
                "date": "45966",
                "firstPrizeCount": lottery_result.prize[0].num,
                "secondPrizeCount": lottery_result.prize[1].num,
                "back": lottery_result.refernumber ? lottery_result.refernumber.split(' ') : [],
                "createTime": lottery_result.opendate,
            }
            // 存储到数据库
            try {
                await writeData(params, 'lotteryHistory');
                successCount++
            } catch (error) {
                errorCount++
            }
        }else {
            skipCount++
        }
        
    }
    // let result = await sysc_hottery_result('dlt')
    res.send({ code: 20000, msg: "操作成功" , data: {
        successCount,errorCount,skipCount
    } })
})

// 修改记录接口
router.post('/updateRecord', async (req, res) => {
    try {
        const {
            type,
            front,
            back,
            firstPrizeCount = 0,
            secondPrizeCount = 0,
            drawNumber
        } = req.body;

        // 验证必要参数
        if (!drawNumber) {
            return res.send({ code: 400, msg: '期号不能为空' });
        }

        // 验证彩种
        const lotteryTypeResult = await readData({ code: type }, 'lotteryTypes');
        if (lotteryTypeResult.data.length === 0) {
            return res.send({ code: 400, msg: '无效的彩票类型' });
        }
        const config = lotteryTypeResult.data[0];

        // 验证记录是否存在
        const existingRecord = await readData({ type, drawNumber }, 'lotteryHistory', true);
        if (!existingRecord.data || Object.keys(existingRecord.data).length === 0) {
            return res.send({ code: 400, msg: '该期号的记录不存在' });
        }

        // 验证前后区号码
        if (!front || !Array.isArray(front) || front.length !== config.front.count) {
            return res.send({ code: 400, msg: `前区号码不合法，需${config.front.count}个号码` });
        }
        if (config.hasBack && (!back || !Array.isArray(back) || back.length !== config.back.count)) {
            return res.send({ code: 400, msg: `后区号码不合法，需${config.back.count}个号码` });
        }

        // 验证号码范围
        const isValidFront = front.every(num =>
            Number.isInteger(num) && num >= config.front.min && num <= config.front.max
        );
        let isValidBack = true;
        if (config.hasBack) {
            isValidBack = back.every(num =>
                Number.isInteger(num) && num >= config.back.min && num <= config.back.max
            );
        }

        if (!isValidFront) {
            return res.send({ code: 400, msg: `前区号码必须在${config.front.min}-${config.front.max}之间` });
        }
        if (config.hasBack && !isValidBack) {
            return res.send({ code: 400, msg: `后区号码必须在${config.back.min}-${config.back.max}之间` });
        }

        // 验证奖项数据
        if (!Number.isInteger(firstPrizeCount) || firstPrizeCount < 0) {
            return res.send({ code: 400, msg: '一等奖注数必须为非负整数' });
        }
        if (!Number.isInteger(secondPrizeCount) || secondPrizeCount < 0) {
            return res.send({ code: 400, msg: '二等奖注数必须为非负整数' });
        }

        // 准备更新的记录
        const updatedRecord = {
            ...existingRecord.data,
            front: [...front].sort((a, b) => a - b),
            back: config.hasBack ? [...back].sort((a, b) => a - b) : [],
            firstPrizeCount,
            secondPrizeCount,
            updateTime: new Date().toISOString() // 添加更新时间
        };

        // 保存更新
        await delData({ type, drawNumber }, 'lotteryHistory'); // 先删除旧记录
        const result = await writeData(updatedRecord, 'lotteryHistory'); // 写入新记录

        res.send({
            code: 20000,
            msg: '记录更新成功',
            data: {
                drawNumber,
                ...result
            }
        });
    } catch (error) {
        res.send({ code: 50000, msg: error.message });
    }
});

// 删除记录接口
router.post('/deleteRecord', async (req, res) => {
    try {
        const { type, drawNumber } = req.body;

        // 验证参数
        if (!type || !drawNumber) {
            return res.send({ code: 400, msg: '彩种类型和期号不能为空' });
        }

        // 验证彩种
        const lotteryTypeResult = await readData({ code: type }, 'lotteryTypes');
        if (lotteryTypeResult.data.length === 0) {
            return res.send({ code: 400, msg: '无效的彩票类型' });
        }

        // 执行删除
        await delData(req.body, 'lotteryHistory');

        res.send({
            code: 20000,
            msg: '记录删除成功',
            data: { drawNumber }
        });
    } catch (error) {
        res.send({ code: 50000, msg: error.message });
    }
});

// 批量导入
router.post('/lotteryImport', async (req, res) => {
    try {

        let result = await writeData(req.body, 'lotteryHistory', true)

        res.send({ code: 20000, msg: '导入成功' });
    } catch (error) {
        res.send({ code: 50000, msg: '导入失败' });
    }
});

// 业务逻辑函数
async function getHistory(type) {
    const result = await readData({ type, page: 1, size: 1000000 }, 'lotteryHistory');
    return result.data || [];
}

async function saveToHistory(type, record) {
    const recordWithDrawNumber = record.drawNumber
        ? record
        : { ...record, drawNumber: await generateUniqueDrawNumber(type) };

    const recordToSave = {
        ...recordWithDrawNumber,
        type,
        timestamp: new Date().toISOString(),
        createTime: new Date().toISOString() // 确保有创建时间字段，用于排序
    };

    return await writeData(recordToSave, 'lotteryHistory');
}

async function generateUniqueDrawNumber(type) {
    const history = await getHistory(type);
    const existingNumbers = new Set(history.map(item => item.drawNumber).filter(num => num !== undefined));

    let drawNumber;
    do {
        drawNumber = Math.floor(Math.random() * MAX_DRAW_NUMBER) + 1;
    } while (existingNumbers.has(drawNumber));

    return drawNumber;
}

async function initializeHistoryData(type, config) {
    const history = await getHistory(type);
    if (history && history.length > 0) return;

    const historyData = [];
    const existingCombinations = new Set();
    let countAdded = 0;

    while (countAdded < INITIAL_DRAWS) {
        // 生成随机号码（复用号码生成逻辑）
        const front = generateRandomSet(config.front.count, config.front.min, config.front.max);
        const back = config.hasBack ? generateRandomSet(config.back.count, config.back.min, config.back.max) : [];
        const comboKey = `${front.join(',')}-${back.join(',')}`;

        if (!existingCombinations.has(comboKey)) {
            existingCombinations.add(comboKey);

            const minAttempts = 1000000;
            const maxAttempts = 200000000;
            const randomAttempts = Math.floor(Math.random() * (maxAttempts - minAttempts + 1)) + minAttempts;

            const today = new Date();
            const threeMonthsAgo = new Date();
            threeMonthsAgo.setMonth(today.getMonth() - 3);
            const randomTime = new Date(threeMonthsAgo.getTime() + Math.random() * (today.getTime() - threeMonthsAgo.getTime()));

            const drawNumber = await generateUniqueDrawNumber(type);

            historyData.push({
                front,
                back,
                attempts: randomAttempts,
                drawNumber: drawNumber,
                timestamp: randomTime.toISOString(),
                createTime: randomTime.toISOString()
            });

            countAdded++;
        }
    }

    historyData.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
    await writeData(historyData, 'lotteryHistory');
}

// 生成纯随机号码组合（供初始化使用）
function generateRandomSet(count, min, max) {
    const numbers = [];
    while (numbers.length < count) {
        const num = Math.floor(Math.random() * (max - min + 1)) + min;
        if (!numbers.includes(num)) numbers.push(num);
    }
    return numbers.sort((a, b) => a - b);
}

module.exports = router;
